package chapter2_9_unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author huayuhao
 * @date 2020/12/16 14:47
 */
public class TestUnsafe2 {

    // 获取Unsafe实例
    static final Unsafe UNSAFE;

    // 记录变量state在类TestUnsafe中的偏移值
    static final long stateOffset;

    // state变量
    private volatile long state = 0;

    static {
        try {
            // 使用反射获取Unsafe的成员变量theUnsafe
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            // 设置为可存取
            field.setAccessible(true);
            // 获取该变量的值
            UNSAFE = (Unsafe) field.get(null);
            // 初始化state变量在类TestUnsafe2中的偏移值
            stateOffset = UNSAFE.objectFieldOffset(TestUnsafe2.class.getDeclaredField("state"));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
            throw new Error(e);
        }
    }

    public static void main(String[] args) {
        TestUnsafe2 testUnsafe = new TestUnsafe2();
        // 如果stateOffset的state变量的值为0,则更新为1
        boolean success = UNSAFE.compareAndSwapInt(testUnsafe, stateOffset, 0, 1);
        System.out.println(success);
    }

}
